package auth

import (
	"context"
	"fast-boot/app/model"
	"fast-boot/common/cachex"
	"fast-boot/common/globalkey"
	"fast-boot/common/xerr"
	"github.com/hwUltra/fb-tools/captchax"
	"github.com/hwUltra/fb-tools/jwtx"
	"github.com/hwUltra/fb-tools/utils"
	"time"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 登录
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.TokenResp, err error) {
	var ct = captchax.NewCaptchaTool(captchax.CaptchaConf{
		Type:      captchax.MathType,
		Store:     captchax.RedisType,
		CacheConf: l.svcCtx.Config.Cache,
	})
	if ok := ct.VerifyCaptcha(req.CaptchaKey, req.CaptchaCode, true); ok == false {
		return nil, xerr.NewErrMsg("验证码错误")
	}
	res := &model.SysUserModel{}
	l.svcCtx.GormClient.GormDb.Where("username = ?", req.UserName).First(res)

	if res.Id == 0 {
		return nil, xerr.NewErrMsg("用户不存在")
	}
	password := utils.PasswordEncrypt(l.svcCtx.Config.Salt, req.Password)
	if password != res.Password {
		return nil, xerr.NewErrMsg("密码错误")
	}

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	accessToken, err := jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, res.Id)
	if err != nil {
		return nil, err
	}
	resp = &types.TokenResp{
		AccessToken:  accessToken,
		RefreshAfter: now + accessExpire,
		AccessExpire: now + accessExpire/2,
	}

	cc := cachex.NewStore(l.svcCtx.Config.Cache)
	_ = cc.Cache.SetWithExpire(cc.FormatPrimary(globalkey.CacheUserTokenKey, res.Id), resp, time.Duration(l.svcCtx.Config.Auth.AccessExpire)*time.Second)

	return resp, nil
}
